package com.lifeverse.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 协作冲突实体类
 * 记录协作过程中的冲突和解决情况
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "collaboration_conflicts", indexes = {
    @Index(name = "idx_collaboration_conflict_task", columnList = "collaboration_task_id"),
    @Index(name = "idx_collaboration_conflict_reporter", columnList = "reporter_id"),
    @Index(name = "idx_collaboration_conflict_type", columnList = "conflict_type"),
    @Index(name = "idx_collaboration_conflict_status", columnList = "resolution_status"),
    @Index(name = "idx_collaboration_conflict_occurred", columnList = "occurred_at")
})
public class CollaborationConflict extends BaseEntity {
    
    /**
     * 协作任务
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "collaboration_task_id", nullable = false)
    private CollaborationTask collaborationTask;
    
    /**
     * 冲突报告者
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reporter_id", nullable = false)
    private LifeEntity reporter;
    
    /**
     * 冲突涉及的参与者1
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "participant1_id", nullable = false)
    private LifeEntity participant1;
    
    /**
     * 冲突涉及的参与者2
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "participant2_id")
    private LifeEntity participant2;
    
    /**
     * 冲突调解者
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "mediator_id")
    private LifeEntity mediator;
    
    /**
     * 冲突类型
     */
    @Column(name = "conflict_type", nullable = false, length = 50)
    private String conflictType;
    
    /**
     * 冲突严重程度（1-10）
     */
    @Column(name = "severity_level", nullable = false)
    private Integer severityLevel;
    
    /**
     * 冲突标题
     */
    @Column(name = "title", nullable = false, length = 200)
    private String title;
    
    /**
     * 冲突描述
     */
    @Column(name = "description", columnDefinition = "TEXT")
    private String description;
    
    /**
     * 冲突发生时间
     */
    @Column(name = "occurred_at", nullable = false)
    private LocalDateTime occurredAt;
    
    /**
     * 冲突发现时间
     */
    @Column(name = "detected_at")
    private LocalDateTime detectedAt;
    
    /**
     * 解决状态
     */
    @Column(name = "resolution_status", nullable = false, length = 20)
    private String resolutionStatus = "OPEN";
    
    /**
     * 解决方案
     */
    @Column(name = "resolution", columnDefinition = "TEXT")
    private String resolution;
    
    /**
     * 解决时间
     */
    @Column(name = "resolved_at")
    private LocalDateTime resolvedAt;
    
    /**
     * 解决耗时（分钟）
     */
    @Column(name = "resolution_time_minutes")
    private Long resolutionTimeMinutes;
    
    /**
     * 冲突影响评分（0-100）
     */
    @Column(name = "impact_score", precision = 5, scale = 2)
    private BigDecimal impactScore;
    
    /**
     * 解决效果评分（0-100）
     */
    @Column(name = "resolution_effectiveness", precision = 5, scale = 2)
    private BigDecimal resolutionEffectiveness;
    
    /**
     * 冲突原因分析
     */
    @Column(name = "root_cause_analysis", columnDefinition = "TEXT")
    private String rootCauseAnalysis;
    
    /**
     * 预防措施
     */
    @Column(name = "prevention_measures", columnDefinition = "TEXT")
    private String preventionMeasures;
    
    /**
     * 学习要点
     */
    @Column(name = "lessons_learned", columnDefinition = "TEXT")
    private String lessonsLearned;
    
    /**
     * 参与者1的观点
     */
    @Column(name = "participant1_perspective", columnDefinition = "TEXT")
    private String participant1Perspective;
    
    /**
     * 参与者2的观点
     */
    @Column(name = "participant2_perspective", columnDefinition = "TEXT")
    private String participant2Perspective;
    
    /**
     * 调解记录
     */
    @Column(name = "mediation_log", columnDefinition = "TEXT")
    private String mediationLog;
    
    /**
     * 冲突标签（JSON格式）
     */
    @Column(name = "tags", length = 500)
    private String tags;
    
    /**
     * 冲突属性（JSON格式）
     */
    @Column(name = "attributes", columnDefinition = "TEXT")
    private String attributes;
    
    /**
     * 相关证据（JSON格式）
     */
    @Column(name = "evidence", columnDefinition = "TEXT")
    private String evidence;
    
    @PrePersist
    protected void onCreate() {
        super.onCreate();
        if (occurredAt == null) {
            occurredAt = LocalDateTime.now();
        }
        if (detectedAt == null) {
            detectedAt = LocalDateTime.now();
        }
    }
    
    /**
     * 开始解决冲突
     */
    public void startResolution(LifeEntity mediator) {
        this.resolutionStatus = "IN_PROGRESS";
        this.mediator = mediator;
    }
    
    /**
     * 解决冲突
     */
    public void resolve(String resolution, BigDecimal effectiveness) {
        this.resolutionStatus = "RESOLVED";
        this.resolution = resolution;
        this.resolvedAt = LocalDateTime.now();
        this.resolutionEffectiveness = effectiveness;
        
        // 计算解决耗时
        if (detectedAt != null) {
            this.resolutionTimeMinutes = java.time.Duration.between(detectedAt, resolvedAt).toMinutes();
        }
    }
    
    /**
     * 关闭冲突（无需解决）
     */
    public void close(String reason) {
        this.resolutionStatus = "CLOSED";
        this.resolvedAt = LocalDateTime.now();
        this.resolution = "冲突关闭: " + reason;
    }
    
    /**
     * 升级冲突
     */
    public void escalate(String reason) {
        this.resolutionStatus = "ESCALATED";
        this.severityLevel = Math.min(10, this.severityLevel + 1);
        this.setRemark((this.getRemark() != null ? this.getRemark() + " | " : "") + "升级原因: " + reason);
    }
    
    /**
     * 判断是否为开放状态
     */
    public boolean isOpen() {
        return "OPEN".equals(resolutionStatus);
    }
    
    /**
     * 判断是否正在解决
     */
    public boolean isInProgress() {
        return "IN_PROGRESS".equals(resolutionStatus);
    }
    
    /**
     * 判断是否已解决
     */
    public boolean isResolved() {
        return "RESOLVED".equals(resolutionStatus);
    }
    
    /**
     * 判断是否已关闭
     */
    public boolean isClosed() {
        return "CLOSED".equals(resolutionStatus);
    }
    
    /**
     * 判断是否已升级
     */
    public boolean isEscalated() {
        return "ESCALATED".equals(resolutionStatus);
    }
    
    /**
     * 判断是否为高严重程度
     */
    public boolean isHighSeverity() {
        return severityLevel >= 7;
    }
    
    /**
     * 判断是否为紧急冲突
     */
    public boolean isUrgent() {
        return severityLevel >= 8;
    }
    
    /**
     * 计算冲突持续时间（分钟）
     */
    public long getConflictDurationMinutes() {
        if (occurredAt == null) {
            return 0;
        }
        
        LocalDateTime endTime = resolvedAt != null ? resolvedAt : LocalDateTime.now();
        return java.time.Duration.between(occurredAt, endTime).toMinutes();
    }
    
    /**
     * 计算检测延迟（分钟）
     */
    public long getDetectionDelayMinutes() {
        if (occurredAt == null || detectedAt == null) {
            return 0;
        }
        
        return java.time.Duration.between(occurredAt, detectedAt).toMinutes();
    }
    
    /**
     * 判断是否涉及特定参与者
     */
    public boolean involvesParticipant(LifeEntity participant) {
        return participant.equals(participant1) || participant.equals(participant2);
    }
    
    /**
     * 获取冲突的另一方参与者
     */
    public LifeEntity getOtherParticipant(LifeEntity participant) {
        if (participant.equals(participant1)) {
            return participant2;
        } else if (participant.equals(participant2)) {
            return participant1;
        }
        return null;
    }
    
    /**
     * 计算解决效率
     */
    public BigDecimal calculateResolutionEfficiency() {
        if (resolutionTimeMinutes == null || resolutionTimeMinutes == 0) {
            return BigDecimal.ZERO;
        }
        
        // 基于严重程度和解决时间计算效率
        // 高严重程度的冲突应该更快解决
        long expectedTime = (11 - severityLevel) * 60; // 严重程度越高，期望解决时间越短
        
        if (resolutionTimeMinutes <= expectedTime) {
            return BigDecimal.valueOf(100);
        } else {
            BigDecimal efficiency = BigDecimal.valueOf(expectedTime)
                    .divide(BigDecimal.valueOf(resolutionTimeMinutes), 4, java.math.RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100));
            return efficiency.max(BigDecimal.ZERO).min(BigDecimal.valueOf(100));
        }
    }
}